package com.yimi.yinhepda.views.offline.unload;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.OffLineScanAdapter;
import com.yimi.yinhepda.db.dao.LoadUnloadGroupTableDao;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.LoadUnLoadGroupTable;
import com.yimi.yinhepda.db.table.ScanDetailVo;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.views.load_module.LoadUnloadGroupActivity;
import com.yimi.yinhepda.views.unload_module.UnloadCompareActivity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 离线卸车扫描界面
 *
 * @author 000432
 */

public class OffLineUnloadActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTitle;
    private TextView mNum;
    /**
     * 卸车添加按钮
     */
    private Button mOfflineAdd;
    /**
     * 卸车删除按钮
     */
    private Button mofflineDelete;
    private ListView mListView;
    /**
     * 退出按钮
     */
    private Button mUnloadBack;
    /**
     * 提交按钮
     */
    private Button mUnloadSubmit;
    /**
     * 票数
     */
    private TextView mTotalPiao;
    /**
     * 件数
     */
    private TextView mTotalJian;
    private UnloadScanTableDao mUnloadScanTableDao;
    private ScanDetailVoDao scanDetailVoDao;
    private UnloadTaskTableDao taskTableDao;
    /**
     * 卸车标志
     */
    private int operTypeCode = 4;
    private List<ScanDetailVo> scanList;
    private OffLineScanAdapter scanAdapter;
    /**
     * 配载单对象
     */
    private UnloadTaskTable taskTable;
    private String userCode;
    public static final int ADD_DELETE_RESULTOK = 100;
    /**
     * 月台号
     */
    private String platformNo;
    /**
     * 装卸参与人工号
     */
    private String joinWrokNum;
    /**
     * 装卸参与人姓名
     */
    private String joinUserName;
    /**
     * 修改装卸人按钮
     */
    private Button btnModifyGroup;
    /**
     * 离线任务号
     */
    private String offlineTaskNo;

    public OffLineUnloadActivity() {
        super(true);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unload_offline);

        initView();
        initEvent();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取装卸组信息
        getGroupInfo();
    }

    public void initView() {
        mTitle =  findViewById(R.id.title);
        mNum =  findViewById(R.id.num);
        mOfflineAdd =  findViewById(R.id.unload_offline_add);
        mofflineDelete =  findViewById(R.id.unload_offline_del);
        mListView =  findViewById(R.id.unload_task_offline);
        mUnloadBack =  findViewById(R.id.unload_offline_back);
        mUnloadSubmit =  findViewById(R.id.unload_offline_submit);
        mTotalPiao =  findViewById(R.id.unload_totle_piao);
        mTotalJian =  findViewById(R.id.unload_totle_jian);
        btnModifyGroup =  findViewById(R.id.btn_modifyLoadUnloadPeople);
    }

    public void initEvent() {
        mOfflineAdd.setOnClickListener(this);
        mofflineDelete.setOnClickListener(this);
        mUnloadBack.setOnClickListener(this);
        mUnloadSubmit.setOnClickListener(this);
        btnModifyGroup.setOnClickListener(this);
    }

    public void initData() {
        //获取装卸组信息
        getGroupInfo();

        mUnloadScanTableDao = new UnloadScanTableDao();
        scanDetailVoDao = new ScanDetailVoDao();
        taskTableDao = new UnloadTaskTableDao();

        mTitle.setText("离线卸车扫描");
        offlineTaskNo = getIntent().getStringExtra("offlineTaskNo");
        //设置未上传数
        mNum.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
        userCode = sharedPreferUtil.getValue(Common.USER_CODE);
        if (offlineTaskNo != null) {
            scanList = scanDetailVoDao.getDataByStowageAndType(offlineTaskNo, operTypeCode, userCode);
            if (scanList == null) {
                scanList = new ArrayList<>();
            }
            List<UnloadTaskTable> stowage = taskTableDao.findStowage(offlineTaskNo, userCode);
            if (stowage != null && !stowage.isEmpty()) {
                taskTable = stowage.get(0);
            }
        }
        //设置总票，总件数
        if (taskTable != null) {
            mTotalPiao.setText(String.valueOf(taskTable.getPriceNum()));
            mTotalJian.setText(String.valueOf(taskTable.getPiecesNum()));
        }

        scanAdapter = new OffLineScanAdapter(this, scanList);
        mListView.setAdapter(scanAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(OffLineUnloadActivity.this, UnloadCompareActivity.class);
                Bundle bundle = new Bundle();
                String waybillNo = scanList.get(position).getWaybillNo();
                bundle.putString("offlineTaskNo", offlineTaskNo);
                bundle.putString("userCode", userCode);
                bundle.putString("waybillNo", waybillNo);
                bundle.putInt("operTypeCode", operTypeCode);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取装卸组信息
     */
    private void getGroupInfo() {
        //获取登录的部门类型
        int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
        if (deptType == 5 || deptType == 6) {
            LoadUnLoadGroupTable loadUnLoadGroupTable = new LoadUnloadGroupTableDao().getData();
            if (loadUnLoadGroupTable != null) {
                platformNo = loadUnLoadGroupTable.getPlatform();
                //登录分拨获取装卸组
                joinWrokNum = loadUnLoadGroupTable.getUserCodes();
                joinUserName = loadUnLoadGroupTable.getUserNames();
            }
            if ((joinWrokNum == null || joinWrokNum.equals("")) && ((joinUserName == null) || joinUserName.equals(""))) {
                joinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
                joinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
                if (joinUserName == null || joinUserName.equals("")) {
                    joinUserName = joinWrokNum;
                }
            } else if (joinUserName == null || joinUserName.equals("")) {
                joinUserName = joinWrokNum;
            }
            btnModifyGroup.setVisibility(View.VISIBLE);
        } else {
            joinWrokNum = sharedPreferUtil.getValue(Common.USER_CODE);
            joinUserName = sharedPreferUtil.getValue(Common.USER_NAME);
            if (joinUserName == null || joinUserName.equals("")) {
                joinUserName = joinWrokNum;
            }
            btnModifyGroup.setVisibility(View.GONE);
        }
        //自动检测没有省区的工号，自动添加上去
        String compCode = sharedPreferUtil.getCompanyCode();
        if(compCode == null || "".equals(compCode)){
            showToast("企业编码为空！");
        }
        String[] userCodes = joinWrokNum.split(",");
        for (int i = 0; i < userCodes.length; i++) {
            String userCode = userCodes[i];
            if (!userCode.contains("@")) {
                userCodes[i] = userCode + "@" + compCode;
            }
        }
        StringBuilder tempUserCodes = new StringBuilder();
        for (String userCode : userCodes) {
            tempUserCodes.append(userCode + ",");
        }
        joinWrokNum = tempUserCodes.substring(0, tempUserCodes.length() - 1);
    }

    @Override
    public String getPageName() {
        return "离线卸车";
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doScan(result);
        }
    }

    /**
     * 处理扫描
     */
    protected void doScan(String result) {

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }
        //判断子单是否已扫
        List<UnloadScanTable> childWaybillNo = mUnloadScanTableDao.getChildWaybillNo(offlineTaskNo, operTypeCode, userCode, result);
        if (childWaybillNo != null && !childWaybillNo.isEmpty()) {
            SoundVibratorManager.playSound(2);
            showToast("运单已扫描!");
            return;
        }
        //判断运单是否存在
        boolean isExitWayBillNo = false;
        String wayBillNo = result.substring(0, 12);
        if (scanList != null && !scanList.isEmpty()) {
            for (int i = 0; i < scanList.size(); i++) {
                ScanDetailVo scanDetailVo = scanList.get(i);
                if (scanDetailVo.getWaybillNo().equals(wayBillNo)) {
                    isExitWayBillNo = true;
                    //更新数据库
                    ScanDetailVo tempEntity = scanDetailVo;
                    tempEntity.setQuantity(tempEntity.getQuantity() + 1);
                    tempEntity.setScanTime(DateHelper.getDateFormateOffline());
                    scanList.remove(i);
                    scanList.add(0, tempEntity);
                    try {
                        scanDetailVoDao.update(tempEntity);
                        //保存运单
                        UnloadScanTable unloadScanTable = saveWaybill(result, 1);
                        mUnloadScanTableDao.insert(unloadScanTable);
                        //更新配载单件数
                        taskTable.setPiecesNum(taskTable.getPiecesNum() + 1);
                        taskTableDao.update(taskTable);
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                    }
                }
            }
        }
        if (!isExitWayBillNo) {
            ScanDetailVo scanDetail = new ScanDetailVo();
            scanDetail.setWaybillNo(wayBillNo);
            scanDetail.setInputType(1);
            scanDetail.setQuantity(1);
            scanDetail.setCreateTime(DateHelper.getDateTimeFormate(null));
            scanDetail.setScanTime(DateHelper.getDateFormateOffline());
            scanDetail.setOfflineTaskNo(offlineTaskNo);
            scanDetail.setOperTypeCode(operTypeCode);
            scanDetail.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
            if (scanList == null) {
                scanList = new ArrayList<>();
            }
            //更新列表
            scanList.add(0, scanDetail);
            //保存运单
            UnloadScanTable unloadScanTable = saveWaybill(result, 1);
            try {
                //不在列表中，更新件数
                taskTable.setPiecesNum(taskTable.getPiecesNum() + 1);
                taskTable.setPriceNum(taskTable.getPriceNum() + 1);
                taskTableDao.update(taskTable);
                scanDetailVoDao.insert(scanDetail);
                mUnloadScanTableDao.insert(unloadScanTable);
            } catch (SQLException e) {
                LogUtil.e(e.toString());
            }
        }

        //设置总票，总件数
        if (taskTable != null) {
            mTotalPiao.setText(String.valueOf(taskTable.getPriceNum()));
            mTotalJian.setText(String.valueOf(taskTable.getPiecesNum()));
        }
        scanAdapter.notifyDataSetChanged();
        SoundVibratorManager.playSound(1);
        //设置未上传数
        mNum.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.unload_offline_add:
                //获取装卸组信息
                getGroupInfo();

                Intent intent = new Intent(this, OffLineUnloadAddActivity.class);
                intent.putExtra("offlineTaskNo", offlineTaskNo);
                intent.putExtra("platformNo", platformNo);
                intent.putExtra("joinUserName", joinUserName);
                intent.putExtra("joinWrokNum", joinWrokNum);
                startActivityForResult(intent, 0);
                break;
            case R.id.unload_offline_del:
                intent = new Intent(this, OffLineUnloadDeleteActivity.class);
                intent.putExtra("offlineTaskNo", offlineTaskNo);
                startActivityForResult(intent, 0);
                break;
            case R.id.unload_offline_back:
                finish();
                break;
            case R.id.unload_offline_submit:
                //提交
                if (scanList == null || scanList.isEmpty()) {
                    showToast(getString(R.string.tmp_no_data));
                    return;
                }
                try {
                    //设置为卸车
                    taskTable.setLoadType(3);
                    taskTableDao.update(taskTable);
                } catch (SQLException e) {
                    LogUtil.e(e.toString());
                }

                intent = new Intent(this, OffLineUnloadSuccessActivity.class);
                intent.putExtra("taskTable", taskTable);
                startActivity(intent);
                finish();
                break;
            case R.id.btn_modifyLoadUnloadPeople:
                intent = new Intent(this, LoadUnloadGroupActivity.class);
                Bundle bundle = new Bundle();
                //扫描类型：1-装车扫描，2-卸车扫描,3-离线装车扫描，4-离线卸车扫描
                bundle.putInt("scanType", 4);
                //装车类型：1-装车，2-卸车,3-离线装车，4-离线卸车
                bundle.putInt("loadType", 4);
                //离线任务号
                bundle.putString("offlineTaskNo", offlineTaskNo);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ADD_DELETE_RESULTOK) {
            offlineTaskNo = data.getStringExtra("offlineTaskNo");
            initData();
        }
    }

    /**
     * 保存运单
     */
    private UnloadScanTable saveWaybill(String result, int type) {
        UnloadScanTable unloadScan = new UnloadScanTable();
        //时间
        unloadScan.setScanTime(Constants.getCurrentTimeFormat1());
        unloadScan.setOperTime(DateHelper.getDateTimeFormate(null));
        // 子单
        unloadScan.setChildWaybillNo(result);
        // 主单
        unloadScan.setWaybillNo(result.substring(0, 12));
        // 扫描类型
        unloadScan.setInputType(type);
        // 操作类型 卸车
        unloadScan.setOperTypeCode(4);
        // 配载单号
        unloadScan.setOfflineTaskNo(offlineTaskNo);
        unloadScan.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
        //设置月台号
        unloadScan.setPlatformNo(platformNo);
        //装卸组参与人
        unloadScan.setOperPersonNames(joinUserName);
        unloadScan.setOperPersonCodes(joinWrokNum);
        return unloadScan;
    }
}
